import React, { useState, useEffect } from "react";
import "./UserList.css";

export default function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 从API获取用户数据
    fetch("http://localhost:8080/api/users/all")
      .then((response) => {
        if (!response.ok) {
          throw new Error("网络响应错误");
        }
        return response.json();
      })
      .then((data) => {
        setUsers(data);
        // 获取每个用户的角色
        fetchUserRoles(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  // 获取用户角色的函数
  const fetchUserRoles = (userList) => {
    const updatedUsers = [...userList];
    let completedRequests = 0;

    userList.forEach((user, index) => {
      fetch("http://localhost:8080/api/users/role", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username: user.username }),
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error(`获取用户 ${user.username} 角色失败`);
          }
          // 注意：根据用户描述，响应是纯文本而不是JSON
          return response.text();
        })
        .then((role) => {
          updatedUsers[index] = { ...user, role };
          completedRequests++;

          // 当所有请求完成后更新状态
          if (completedRequests === userList.length) {
            setUsers(updatedUsers);
          }
        })
        .catch((error) => {
          console.error(error);
          completedRequests++;
        });
    });
  };

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return <div className="error">错误: {error}</div>;
  }

  return (
    <div className="user-list-container">
      <h1>用户列表</h1>
      <div className="user-table-container">
        <table className="user-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>姓名</th>
              <th>邮箱</th>
              <th>角色</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user) => (
              <tr key={user.id}>
                <td>{user.id}</td>
                <td>{user.username}</td>
                <td>{user.email}</td>
                <td>{user.role || "普通用户"}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
